package com.wshl.aijiuunion.controller.activity;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.CustomDownloadFailedListener;
import com.allenliu.versionchecklib.v2.callback.CustomDownloadingDialogListener;
import com.allenliu.versionchecklib.v2.callback.CustomVersionDialogListener;
import com.allenliu.versionchecklib.v2.callback.ForceUpdateListener;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.SPUtils;
import com.wshl.aijiuunion.BaseActivity;
import com.wshl.aijiuunion.GlobConstant;
import com.wshl.aijiuunion.HomeActivity;
import com.wshl.aijiuunion.R;
import com.wshl.aijiuunion.callback.RequestCallback;
import com.wshl.aijiuunion.model.RequestModel;
import com.wshl.aijiuunion.utils.DataCleanManager;
import com.wshl.aijiuunion.utils.DialogUtil;
import com.wshl.aijiuunion.utils.share.LoginOutUtils;
import com.wshl.aijiuunion.view.bean.CheckVersionBean;
import com.wshl.aijiuunion.view.bean.EventBeans;
import com.wshl.aijiuunion.view.widget.NofastClickTextview;

import org.greenrobot.eventbus.EventBus;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created buy 风凊扬 on 2019/10/29 0029
 */
public class SetActivity extends BaseActivity {
    @BindView(R.id.img_back)
    ImageView imgBack;
    @BindView(R.id.tv_top_title)
    TextView tvTopTitle;
    @BindView(R.id.tv_clear_cache)
    NofastClickTextview tvClearCache;
    @BindView(R.id.tv_cache)
    TextView tvCache;
    @BindView(R.id.tv_check_version)
    NofastClickTextview tvCheckVersion;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.tv_edit_pwd)
    NofastClickTextview tvEditPwd;
    @BindView(R.id.tv_loginout)
    NofastClickTextview tvLoginout;
    @BindView(R.id.tv_kefu)
    NofastClickTextview tvKefu;
    @BindView(R.id.tv_zhuxiao)
    NofastClickTextview tvZhuxiao;

    private RequestModel model;

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_set;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        tvTopTitle.setText("设置");

        model = new RequestModel();
        String totalCacheSize = null;
        try {
            totalCacheSize = DataCleanManager.getTotalCacheSize(this);
            tvCache.setText(totalCacheSize);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String appVersionName = AppUtils.getAppVersionName();
        tvVersion.setText(appVersionName);
    }

    @Override
    protected void onResume() {
        super.onResume();
        int isShowVideo = SPUtils.getInstance().getInt(GlobConstant.ISSHOWVIDEO, 0);
        if (isShowVideo == 0) {
            tvZhuxiao.setVisibility(View.VISIBLE);
        } else {
            tvZhuxiao.setVisibility(View.GONE);
        }

    }

    @OnClick({R.id.tv_kefu, R.id.tv_zhuxiao, R.id.img_back, R.id.tv_clear_cache, R.id.tv_check_version, R.id.tv_edit_pwd, R.id.tv_loginout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_kefu:
                String kefutel = SPUtils.getInstance().getString(GlobConstant.KEFUTEL);
                if (!TextUtils.isEmpty(kefutel)) {
                    Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + kefutel));
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivity(intent);
                }
                break;
            case R.id.tv_zhuxiao:
                DialogUtil.showNormaldialog(SetActivity.this, "确定要注销该账户吗?", false, true);
                DialogUtil.setOndialgConfirm(new DialogUtil.OnDialogConfirm() {
                    @Override
                    public void setConfirm() {
                        zhuxiao();

                    }

                    @Override
                    public void setCancel() {

                    }

                    @Override
                    public void getInput(String input) {

                    }
                });
                break;
            case R.id.img_back:
                this.finish();
                break;
            case R.id.tv_clear_cache:
                DialogUtil.showNormaldialog(SetActivity.this, "是否要清除缓存?", false, true);
                DialogUtil.setOndialgConfirm(new DialogUtil.OnDialogConfirm() {
                    @Override
                    public void setConfirm() {
                        //清除aijiu文件夹下的文件
                        FileUtils.deleteAllInDir(GlobConstant.SDCARD_DIR + File.separator + GlobConstant.DEFAULT_CACHE_DIR);
                        DataCleanManager.clearAllCache(SetActivity.this);//清除缓存
                        String totalCacheSize = null;
                        try {
                            totalCacheSize = DataCleanManager.getTotalCacheSize(SetActivity.this);
                            tvCache.setText(totalCacheSize);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void setCancel() {

                    }

                    @Override
                    public void getInput(String input) {

                    }
                });
                break;
            case R.id.tv_check_version:

                checkVersion();


                //  downLoadApk();
                break;
            case R.id.tv_edit_pwd:
                ActivityUtils.startActivity(SetActivity.this, EditPwdActivity.class);
                break;
            case R.id.tv_loginout:
//                String mobile = SPUtils.getInstance().getString(GlobConstant.MOBILE);
//                SPUtils.getInstance().clear();
//                SPUtils.getInstance().put(GlobConstant.MOBILE, mobile);
//                //SPUtils.getInstance().put(GlobConstant.ISSTARTMIAN, true);
//                ToastUtils.showLong(getString(R.string.logintimeout));
//                EventBus.getDefault().post(new EventBeans(GlobConstant.FINISHACLLACTIVITY));
//                ActivityUtils.startActivity(SetActivity.this, LoginActivity.class);

                //清除aijiu文件夹下的文件
                FileUtils.deleteAllInDir(GlobConstant.SDCARD_DIR + File.separator + GlobConstant.DEFAULT_CACHE_DIR);
                DataCleanManager.clearAllCache(SetActivity.this);//清除缓存

                LoginOutUtils.loginout(SetActivity.this);
                break;
        }
    }

    private void zhuxiao() {

        model.zhuxiao(this, new RequestCallback() {
            @Override
            public void onSuccess(String response) {

                SPUtils.getInstance().clear();
                SPUtils.getInstance().put(GlobConstant.ISSTARTMIAN, true);
                EventBus.getDefault().post(new EventBeans(GlobConstant.FINISHACLLACTIVITY));
                ActivityUtils.startActivity(SetActivity.this, HomeActivity.class);

            }

            @Override
            public void onError(int code) {

            }

            @Override
            public void onIntentError() {

            }
        });
    }

    private void checkVersion() {

        model.checkVersion(SetActivity.this, tvVersion.getText().toString(), true, new RequestCallback() {
            @Override
            public void onSuccess(String response) {

                CheckVersionBean checkVersionBean = GsonUtils.fromJson(response, CheckVersionBean.class);
                CheckVersionBean.DataBean data = checkVersionBean.getData();
                String url = data.getUrl();
                String version = data.getVersion();
                String content = data.getContent();
                downLoadApk(url, "发现新版本:" + version + "\n" + content);
            }

            @Override
            public void onError(int code) {

            }

            @Override
            public void onIntentError() {

            }
        });
    }

    private void downLoadApk(String url, final String content) {
        DownloadBuilder downloadBuilder = AllenVersionChecker
                .getInstance()
                .downloadOnly(
                        UIData.create().setDownloadUrl(url)
                );

        downloadBuilder.setForceRedownload(true);
        downloadBuilder.setCustomVersionDialogListener(new CustomVersionDialogListener() {
            @Override
            public Dialog getCustomVersionDialog(Context context, UIData versionBundle) {


                View view1 = LayoutInflater.from(SetActivity.this).inflate(R.layout.dialog_update, null);
                final Dialog dialog = new Dialog(context, R.style.myDialog);
                TextView tvContent = view1.findViewById(R.id.tv_versioncontent);
                tvContent.setText(content);
                dialog.setContentView(view1);
                return dialog;


            }
        });

        //设置这个监听,表示要强制更新,下载时的dialog不能被取消
        downloadBuilder.setForceUpdateListener(new ForceUpdateListener() {
            @Override
            public void onShouldForceUpdate() {


            }
        });


        downloadBuilder.setShowDownloadingDialog(true);//是否显示下载进度对话框
        downloadBuilder.setCustomDownloadingDialogListener(new CustomDownloadingDialogListener() {
            @Override
            public Dialog getCustomDownloadingDialog(Context context, int progress, UIData versionBundle) {


                Dialog baseDialog = new Dialog(context, R.style.myDialog);
                View view = LayoutInflater.from(SetActivity.this).inflate(R.layout.dialog_download, null);
                baseDialog.setContentView(view);
                baseDialog.setCancelable(false);
                return baseDialog;
            }

            //下载中会不断回调updateUI方法
            @Override
            public void updateUI(Dialog dialog, int progress, UIData versionBundle) {
                TextView tvProgress = dialog.findViewById(R.id.tv_download_progress);
                ProgressBar progressBar = dialog.findViewById(R.id.progressBar);
                progressBar.setProgress(progress);
                tvProgress.setText(getString(R.string.versionchecklib_progress, progress));
            }
        });

        downloadBuilder.setCustomDownloadFailedListener(new CustomDownloadFailedListener() {
            @Override
            public Dialog getCustomDownloadFailed(Context context, UIData versionBundle) {

                Dialog baseDialog = new Dialog(context, R.style.myDialog);
                View view = LayoutInflater.from(SetActivity.this).inflate(R.layout.dialog_faild, null);
                baseDialog.setContentView(view);
                //   baseDialog.setCancelable(false);
                return baseDialog;

            }
        });
        downloadBuilder.executeMission(SetActivity.this);
    }
}
